package com.tmpt.freemarker.exec;

import com.tmpt.dto.*;
import com.tmpt.service.ITemplateService;
import com.tmpt.utils.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wxy on 2017/1/28.
 */
public class FmPageUtils {

    public A1TemplateTableDto templateTable;
    private ITemplateService templateService;
    private String _keyRandom = "";

    public FmPageUtils(ITemplateService templateService, A1TemplateTableDto templateTable, String _keyRandom) {
        this._keyRandom = _keyRandom;
        this.templateService = templateService;
        this.templateTable = templateTable;
    }

    /*public static void main(String[] args) {
        Controller controller = new Controller();
        controller.initTemplateTable();
        controller.genTemplate();
    }*/


    /*public void genTemplate(){

        Map<String, Object> columnsTag = getColumnList();

        String templateTableColumnOptionJson = getTemplateTableColumnOptionJson();
        String tableName = templateTable.getTableName();
        String tableNameFirstWordUpper = FmUtils.firstWord2Upper(tableName);
        String tableNameFirstWordLower = FmUtils.firstWord2Lower(tableName);
        List<A1TemplateColumnDto> conditionColumnList = getConditionColumnList();

        Map map = new HashMap();
        map.put("path", prjPath);
        map.put("_keyRandom", _keyRandom);
        map.put("columnsTag", columnsTag);
        map.put("templateTable", templateTable);
        map.put("primaryKey", templateTable.getPrimaryKey());
        map.put("tableName", tableName);
        map.put("templateTableColumnOptionJson", templateTableColumnOptionJson);
        map.put("rightMenuContext", getRightMenuList());
        map.put("templateTableColumnOptionList", getTemplateTableColumnOptionList());
        //map.put("conditionPage", "conditionNorth_"+tableName+".jsp");
        map.put("tableNameFirstWordUpper", tableNameFirstWordUpper);
        map.put("tableNameFirstWordLower", tableNameFirstWordLower);
        map.put("conditionColumnList", conditionColumnList);
        map.put("sortColumnList", getSortColumnList());

    }*/


    /*public void initTemplateTable(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        templateService = (ITemplateService) ctx.getBean("templateService");
        templateTable = templateService.getTemplateTable(_keyRandom);
    }*/

    public Map<String, Object> getColumnList(Map<String,Map<String,String>> dbcolumnsProperty, Map<String,String> columnTableMap) {
        List<A1TemplateColumnDto> columnList = templateTable.getA1TemplateColumnDtoList();
        int hasCheckbox = templateTable.getHasCheckbox();

        List<Map<String,Object>> column4Add = new ArrayList<Map<String,Object>>();//add and edit dialog
        JSONArray jarrColumn = new JSONArray();
        JSONArray jarrColumn_frozen = new JSONArray();
        JSONObject defaultValueJO = new JSONObject();
        //checkbox框
        if (hasCheckbox == 1) {
            JSONObject jo = new JSONObject();
            jo.put("field", "ck");
            jo.put("checkbox", "true");
            jarrColumn.put(jo);
        }
        for (A1TemplateColumnDto a1TemplateColumnDto : columnList) {
            String columnName = a1TemplateColumnDto.getColumnName();
            String propertyName = FmUtils.switch2Property(columnName);
            String propertyNameFirstWordUpper = FmUtils.firstWord2Upper(propertyName);
            //String columnType = a1TemplateColumnDto.getColumnType();
            String columnShowName = a1TemplateColumnDto.getColumnShowName();
            int isFrozenColumn = a1TemplateColumnDto.getIsFrozenColumn();
            int isHidden = a1TemplateColumnDto.getIsHidden();
            int canAdd = a1TemplateColumnDto.getCanAdd();
            int columnWidth = a1TemplateColumnDto.getColumnWidth();
            int isSortColumn = a1TemplateColumnDto.getIsSortColumn();
            int dataResource = a1TemplateColumnDto.getDataResource();
            //列在DB中的类型
            String dbColumnDataType = "";
            Map<String,String> dbColumnPropertyMap = dbcolumnsProperty.get(columnTableMap.get(columnName)+"_"+columnName);
            if(dbColumnPropertyMap!=null){
                dbColumnDataType = dbColumnPropertyMap.get("data_type");
            }
            //System.out.println("----------------isSortColumn----"+isSortColumn);
            /*if (isHidden == 1) { //可能是主键ID,页面不展示
                continue;
            }*/
            if (isFrozenColumn == 1) {
                JSONObject jo_frozen = new JSONObject();
                /*if(!StringUtils.isNull(dbColumnDataType) && (dbColumnDataType.equals("date")
                        || dbColumnDataType.equals("datetime")  || dbColumnDataType.equals("timestamp"))){
                    jo_frozen.put("field", propertyName+"_Str");
                }else {
                    jo_frozen.put("field", propertyName);
                }*/
                jo_frozen.put("field", propertyName);
                if (isHidden == 1) { //可能是主键ID,页面不展示
                    jo_frozen.put("hidden", "true");
                }
                jo_frozen.put("title", columnShowName);
                if (columnWidth != 0) {
                    jo_frozen.put("width", columnWidth);
                }else{
                    jo_frozen.put("width", 100);
                }
                if (isSortColumn == 1) {
                    jo_frozen.put("sortable", "true");
                }

                jarrColumn_frozen.put(jo_frozen);
            } else {
                JSONObject jo = new JSONObject();
                /*if(dbColumnDataType.equals("date")
                        || dbColumnDataType.equals("datetime")  || dbColumnDataType.equals("timestamp")){
                    jo.put("field", propertyName+"_Str");
                }else */if(dataResource == A1TemplateColumnDto.dataResource_OptionsTable
                        /*|| dataResource == A1TemplateColumnDto.dataResource_OptionsTableKeyEqualValue*/
                        || dataResource == A1TemplateColumnDto.dataResource_ColumnOptionData){//Enum中取数据，model中列加了_Str，取显示，如：deleteflag_Str
                    //加上，编辑时可能用
                    JSONObject jo1 = new JSONObject();
                    jo1.put("field", propertyName);
                    jo1.put("title", columnShowName);
                    jo1.put("hidden", "true");
                    jarrColumn.put(jo1);
                    //
                    jo.put("field", propertyName+"_Str");
                }
                else {
                    jo.put("field", propertyName);
                }
                if (isHidden == 1) { //可能是主键ID,页面不展示
                    jo.put("hidden", "true");
                }
                jo.put("title", columnShowName);
                if (columnWidth != 0) {
                    jo.put("width", columnWidth);
                }else{
                    jo.put("width", 100);
                }
                if (isSortColumn == 1) {
                    jo.put("sortable", "true");
                }
                jarrColumn.put(jo);
            }
            if (canAdd == 1) {
                Map<String,Object> map = FmUtils.transBean2Map(a1TemplateColumnDto);
                map.put("propertyNameFirstWordUpper",propertyNameFirstWordUpper);
                if(a1TemplateColumnDto.getColumnTip()==null){
                    map.put("columnTip", "");
                }
                if(a1TemplateColumnDto.getDataOptions4AddDialog()==null){
                    map.put("dataOptions4AddDialog","");
                }
                if(a1TemplateColumnDto.getColumnLayoutStyle4adddialog()==null){
                    map.put("columnLayoutStyle4adddialog","");
                }
                map.put("propertyName", FmUtils.switch2Property(a1TemplateColumnDto.getColumnName()));
                System.out.println("========>map:"+map);
                System.out.println("================>columnLayoutStyle4adddialog:"+a1TemplateColumnDto.getColumnLayoutStyle4adddialog());
                column4Add.add(map);
            }
            //Default value
            String defaultValue = a1TemplateColumnDto.getDefaultValue();
            if(!StringUtils.isNull(defaultValue)) {
                defaultValueJO.put(propertyName, defaultValue);
            }
        }


        //行尾Button
        //jsonObject
        JSONObject joOpt = new JSONObject();
        joOpt.put("field", "opt");
        joOpt.put("title", "操作");
        joOpt.put("align", "center");
        //
        StringBuilder sbLineTail = new StringBuilder();
        StringBuilder sbLineTailAuth = new StringBuilder();
        sbLineTail.append("function(value,rowData,rowIndex){");
        sbLineTail.append("if(typeof(rowData.id) == 'undefined'){return '';};");
        sbLineTail.append("var btn = '';");
        int buttonCount = 0;
        //行尾BUTTON
        List<A1TemplateLineTailMenuDto> lineTailMenuDtoList = templateTable.getA1TemplateLineTailMenuDtoList();
        for (A1TemplateLineTailMenuDto lineTailMenuDto : lineTailMenuDtoList) {
            buttonCount++;
            lineTailMyButton(lineTailMenuDto,sbLineTail, sbLineTailAuth);
        }
        //是否有Edit button
        if (templateTable.getHasEditBtn() == 1) {
            buttonCount++;
            lineTailEditButton(sbLineTail, sbLineTailAuth);
        }
        if (templateTable.getHasEditBtn() == 2){
            buttonCount++;
            lineTailEditButton(sbLineTail, sbLineTailAuth);
            buttonCount++;
            lineTailRemoveButton(sbLineTail, sbLineTailAuth);
        }
        if(templateTable.getHasEditBtn() == 3){
            buttonCount++;
            lineTailRemoveButton(sbLineTail,sbLineTailAuth);
        }
        /*//是否有History button
        if (templateTable.getHasHistoryBtn() == 1) {
            buttonCount++;
            //sbLineTail.append("btn += '<a class=\"delcls\" onclick=\"historyRow(\\''+rowIndex+'\\')\" href=\"javascript:void(0)\">历史</a>';");
            sbLineTail.append("btn += '<a class=\"delcls\" onclick=\"historyRow('+rowIndex+')\" href=\"javascript:void(0)\">历史</a>';");
        }*/
        sbLineTail.append(" return btn;}");
        if (buttonCount != 0) {
            joOpt.put("width", buttonCount * 70 + 20);
        }
        //System.out.println(sbLineTail.toString());
        joOpt.put("formatter", "#" + sbLineTail.toString() + "$");
        jarrColumn.put(joOpt);
        String jarrColumnStr = jarrColumn.toString();
        jarrColumnStr = jarrColumnStr.replace("\"#", "").replace("$\"", "");

        for (Map<String, Object> mm:column4Add){
            System.out.println("------------>"+mm);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("columns", jarrColumnStr);
        map.put("lineTailAuth", sbLineTailAuth.toString());
        map.put("frozenColumns", jarrColumn_frozen.toString());
        map.put("column4Add", column4Add);
        map.put("toolbarBtns", getToolbarBtns());
        map.put("defaultValueJOStr", defaultValueJO.toString());

        return map;
    }

    private void lineTailEditButton(StringBuilder sbLineTail,StringBuilder sbLineTailAuth){
        sbLineTail.append("btn += '<a linetail=\"edit\" class=\"editcls\" style=\"height:20px;\" onclick=\"editRow('+rowIndex+')\" href=\"javascript:void(0)\">编辑</a>';");
        //auth
        sbLineTailAuth.append("\t$(\"[linetail='edit']\").hide();").append("\r\n");
        sbLineTailAuth.append("\tauthRequestUrl(_formEditAction,function(authResult){").append("\r\n");
        sbLineTailAuth.append("\t\tif(authResult){").append("\r\n");
        sbLineTailAuth.append("\t\t\t$(\"[linetail='edit']\").show();").append("\r\n");
        sbLineTailAuth.append("\t\t}").append("\r\n");
        sbLineTailAuth.append("\t});").append("\r\n");
    }
    private void lineTailRemoveButton(StringBuilder sbLineTail,StringBuilder sbLineTailAuth){
        sbLineTail.append("btn += '<a linetail=\"del\" class=\"delcls\" style=\"height:20px;\" onclick=\"removeRow('+rowIndex+')\" href=\"javascript:void(0)\">删除</a>';");
        //auth
        sbLineTailAuth.append("\t$(\"[linetail='del']\").hide();").append("\r\n");
        sbLineTailAuth.append("\tauthRequestUrl(_formRemoveAction,function(authResult){").append("\r\n");
        sbLineTailAuth.append("\t\tif(authResult){").append("\r\n");
        sbLineTailAuth.append("\t\t\t$(\"[linetail='del']\").show();").append("\r\n");
        sbLineTailAuth.append("\t\t}").append("\r\n");
        sbLineTailAuth.append("\t});").append("\r\n");
    }

    private void lineTailMyButton(A1TemplateLineTailMenuDto lineTailMenuDto,StringBuilder sbLineTail,StringBuilder sbLineTailAuth){
        long id = lineTailMenuDto.getId();
        String idStr = String.valueOf(id);
        String itemName = lineTailMenuDto.getItemName();
        String url = lineTailMenuDto.getUrl();
        int isDialog = lineTailMenuDto.getIsDialog();
        int width = lineTailMenuDto.getWidth();
        int height = lineTailMenuDto.getHeight();
        String function = "btn += '<a linetail=\"mybtn##?\" class=\"editcls\" style=\"height:20px;\" onclick=lineTailBtnOnClick(\"##1\",\"##2\",\"##3\",\"##4\",\"##5\",'+rowIndex+') href=\"javascript:void(0)\">##6</a>';";
        function = function.replace("##1", url);
        function = function.replace("##2", String.valueOf(isDialog));
        function = function.replace("##3", String.valueOf(width));
        function = function.replace("##4", String.valueOf(height));
        function = function.replace("##5", itemName);
        function = function.replace("##6", itemName);
        function = function.replace("##?", idStr);
        sbLineTail.append(function);
        //auth
        sbLineTailAuth.append("\t$(\"[linetail='mybtn"+idStr+"']\").hide();").append("\r\n");
        sbLineTailAuth.append("\tauthRequestUrl('"+url+"',function(authResult){").append("\r\n");
        sbLineTailAuth.append("\t\tif(authResult){").append("\r\n");
        sbLineTailAuth.append("\t\t\t$(\"[linetail='mybtn"+idStr+"']\").show();").append("\r\n");
        sbLineTailAuth.append("\t\t}").append("\r\n");
        sbLineTailAuth.append("\t});").append("\r\n");

    }

    /**
     * 工具栏button
     * @return
     */
    public Map<String,String> getToolbarBtns(){
        Map<String,String> resultMap = new HashMap<String, String>();
        StringBuilder sb = new StringBuilder();
        StringBuilder sbCtl = new StringBuilder();

        List<A1TemplateToolbarBtnDto> a1TemplateToolbarBtnDtoList = templateTable.getA1TemplateToolbarBtnDtoList();
        int btnIndex = 0;

        //是否有添加button
        if(templateTable.getHasAddBtn() == 1){
            sb.append("datagrid_toolbarBtns[datagrid_toolbarBtns.length] = {").append("\r\n");
            sb.append(" id:'toolbarAddBtnId',text:'添加',").append("\r\n");
            sb.append(" iconCls:'icon-add',").append("\r\n");
            sb.append(" handler:function(){toolbar_add();}").append("\r\n");
            sb.append("}").append("\r\n");
            sbCtl.append("\tif (isFirstLoadSuccess) {").append("\r\n");
            sbCtl.append("\t$('#toolbarAddBtnId').hide();").append("\r\n");
            sbCtl.append("\tauthRequestUrl(_formAddAction,function(authResult){").append("\r\n");
            sbCtl.append("\t if(authResult){").append("\r\n");
            sbCtl.append("\t     $('#toolbarAddBtnId').show();").append("\r\n");
            sbCtl.append("\t  }").append("\r\n");
            sbCtl.append("\t});").append("\r\n");
            sbCtl.append("\tisFirstLoadSuccess = false;").append("\r\n");
            sbCtl.append("\t}").append("\r\n");
            btnIndex++;
        }
        //是否有报表下载button
        if(templateTable.getHasDownloadReportBtn() == 1){
            sb.append("datagrid_toolbarBtns[datagrid_toolbarBtns.length] = {").append("\r\n");
            sb.append("   id:'toolbarReportBtnId',text:'报表下载',").append("\r\n");
            sb.append("   iconCls:'icon-save',").append("\r\n");
            sb.append("   handler:function(){downloadReport();}").append("\r\n");
            sb.append("}").append("\r\n");
            sbCtl.append("\t$('#toolbarReportBtnId').hide();").append("\r\n");
            sbCtl.append("\tauthRequestUrl(_formReportUrl,function(authResult){").append("\r\n");
            sbCtl.append("\t if(authResult){").append("\r\n");
            sbCtl.append("\t     $('#toolbarReportBtnId').show();").append("\r\n");
            sbCtl.append("\t  }").append("\r\n");
            sbCtl.append("\t});").append("\r\n");
            btnIndex++;
        }
        for(A1TemplateToolbarBtnDto a1TemplateToolbarBtnDto:a1TemplateToolbarBtnDtoList){
            long toolbarBtnId = a1TemplateToolbarBtnDto.getId();
            String itemName = a1TemplateToolbarBtnDto.getItemName();
            String url = a1TemplateToolbarBtnDto.getUrl();
            int isDialog = a1TemplateToolbarBtnDto.getIsDialog();
            int width = a1TemplateToolbarBtnDto.getWidth();
            int height  = a1TemplateToolbarBtnDto.getHeight();
            String function = "function(){toolbarBtnOnClick('##1','##2','##3','##4','##5');}";
            function = function.replace("##1", url);
            function = function.replace("##2", String.valueOf(isDialog));
            function = function.replace("##3", String.valueOf(width));
            function = function.replace("##4", String.valueOf(height));
            function = function.replace("##5", itemName);

            sb.append("datagrid_toolbarBtns[datagrid_toolbarBtns.length] = {").append("\r\n");
            sb.append("   id:'toolbarBtnId").append(toolbarBtnId).append("',text:'").append(itemName).append("',").append("\r\n");
            sb.append("   iconCls:'icon-add',").append("\r\n");
            sb.append("   handler:"+function).append("\r\n");
            sb.append("}").append("\r\n");
            sbCtl.append("\t$('#toolbarBtnId"+toolbarBtnId+"').hide();").append("\r\n");
            sbCtl.append("\tauthRequestUrl('").append(url).append("',function(authResult){").append("\r\n");
            sbCtl.append("\t if(authResult){").append("\r\n");
            sbCtl.append("\t     $('#toolbarBtnId"+toolbarBtnId+"').show();").append("\r\n");
            sbCtl.append("\t  }").append("\r\n");
            sbCtl.append("\t});").append("\r\n");
            btnIndex++;
        }
        resultMap.put("buttonInit",sb.toString());
        resultMap.put("buttonAuth",sbCtl.toString());
        return resultMap;
    }


    /**
     * 多值选择，key-value形式; case status when 1 then '有效' when 0 then '无效' end
     * @return
     */
    public String getTemplateTableColumnOptionJson(){
        String jsonArrayColumnOptionsStr = templateService.getTemplateTableColumnOptionJson(_keyRandom);
        return jsonArrayColumnOptionsStr;
    }


    public List<A1TemplateRightMenuDto> getRightMenuList(){
        List<A1TemplateRightMenuDto> rightMenuDtoList = templateTable.getA1TemplateRightMenuDtoList();
        return rightMenuDtoList;
    }


    /**
     * 取查询排序属性条件列表
     * @return
     * */
    public List<A1TemplateColumnDto> getSortColumnList(){
        List<A1TemplateColumnDto> a1TemplateColumnDtoRemoveList = new ArrayList<A1TemplateColumnDto>();
        List<A1TemplateColumnDto> a1TemplateColumnDtoList = new ArrayList<A1TemplateColumnDto>();
        a1TemplateColumnDtoList.addAll(templateTable.getA1TemplateColumnDtoList());
        for(A1TemplateColumnDto a1TemplateColumnDto : a1TemplateColumnDtoList){
            //不是排序属性
            if(a1TemplateColumnDto.getIsSortColumn() == 0){
                a1TemplateColumnDtoRemoveList.add(a1TemplateColumnDto);
                continue;
            }
        }
        a1TemplateColumnDtoList.removeAll(a1TemplateColumnDtoRemoveList);
        //页面上是<s:select> pagecontext不行，一定要session,原因不明
        //pageContext.getSession().setAttribute("sortColumnList", a1TemplateColumnDtoList);

        return a1TemplateColumnDtoList;
    }


    /**
     * 多值选择，key-value形式; case status when 1 then '有效' when 0 then '无效' end
     * @return
     */
    public List<Map<String,Object>> getTemplateTableColumnOptionList(){
        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();

        List<A1TemplateColumnDto> a1TemplateColumnDtoList = templateService.getTemplateTableColumnOptionList(_keyRandom);
        for(A1TemplateColumnDto a1TemplateColumnDto : a1TemplateColumnDtoList){
            Map<String,Object> map = FmUtils.transBean2Map(a1TemplateColumnDto);
            String propertyName = FmUtils.switch2Property(a1TemplateColumnDto.getColumnName());
            map.put("propertyName",propertyName);
            map.put("propertyNameFirstWordUpper",FmUtils.firstWord2Upper(propertyName));
            list.add(map);
            System.out.println("---map:"+map);
        }

        return list;
    }
}
